const router = require('koa-router')()

// 获取管理员信息
router.get('/getmanage', async function (ctx, next) {
    let sql = "select * from manage";
    let result = await ctx.db.EXCUTE(sql);
    ctx.body = { data: result, status: "获取管理员信息成功" }
})

// 搜索管理员信息
router.post('/selmanage', async function (ctx, next) {
    let manageName = ctx.request.body.managename;
    let sql = `select * from manage where managename like '%${manageName}%'`;
    let result = await ctx.db.EXCUTE(sql);
    if (result == '') {
        ctx.body = { status: "没有该管理员消息，请重新输入" }
    } else {
        ctx.body = { data: result, status: "查找管理员信息成功" }
    }
})

// 提交管理员信息
var fs = require('fs');
router.post('/addmanage', async function (ctx, next) {
    let res = ctx.request.body
    let imgurl = ""
    if (res.avaimg !== "") {
        let file = res.avaimg;
        let basePath = './public/manageavater/';
        let filename = Date.now() + '.webp'
        let filePath = basePath + filename;
        // 存到文件夹
        const base64 = file.replace(/^data:image\/\w+;base64,/, "")
        const dataBuffer = Buffer.from(base64, 'base64')
        fs.writeFile(filePath, dataBuffer, function (err) {//用fs写入文件
            if (err) {
                console.log(err);
            } else {
                console.log("成功")
            }
        })
        imgurl = filename
    }
    let formdata = {
        avaimg: imgurl,
        managename: res.managename,
        phone: res.phone,
        email: res.email,
        password: res.password,
        address: res.address,
        id: parseInt(Math.random() * 100000)
    }
    let sql = `insert into manage values (?,?,?,?,?,?,?)`
    await ctx.db.EXCUTE(sql, [formdata.id, formdata.managename, formdata.phone, formdata.email, formdata.avaimg, formdata.password, formdata.address]);
    ctx.body = { status: "提交管理员信息成功" }
})

// 修改管理员信息
var path = require('path')
router.post('/editmanage', async function (ctx, next) {
    let res = ctx.request.body
    if (res.avaimg.split(".")[2] == "webp") {
        // 有图片且未修改
        let arr = res.avaimg.split("/")[2]
        let arr1 = arr.split('.')
        let imgurl = arr1[0] + "." + arr1[2]
        let sql = `update manage set managename=?,phone=?,email=?,avaimg=?,password=?,address=? where id = ?`;
        await ctx.db.EXCUTE(sql, [res.managename, res.phone, res.email, imgurl, res.password, res.address, res.id]);
    } else {
        // 有图片且修改
        let imgname = res.img
        let basePath = './public/manageavater/';
        let file = res.avaimg;
        if (imgname !== '') {
            let arr = imgname.split("/")[2]
            let arr1 = arr.split('.')
            let name = arr1[0] + "." + arr1[2]
            var files = [];
            if (fs.existsSync(basePath)) {
                files = fs.readdirSync(basePath);
                files.forEach(function (file, index) {
                    var curPath = path.join(basePath, file);
                    if (fs.statSync(curPath).isDirectory()) {
                        deleteFile(curPath, file);
                    } else {
                        if (file.indexOf(name) > -1) {
                            fs.unlinkSync(curPath);
                        }
                    }
                });
            } else {
                console.log("给定的路径不存在！");
            }
        }
        let filename = Date.now() + '.webp'
        let filePath = basePath + filename;
        // 存到文件夹
        const base64 = file.replace(/^data:image\/\w+;base64,/, "")
        const dataBuffer = Buffer.from(base64, 'base64')
        fs.writeFile(filePath, dataBuffer, function (err) {//用fs写入文件
            if (err) {
                console.log(err);
            } else {
                console.log("成功")
            }
        })
        let imgurl = filename
        let sql = `update manage set managename=?,phone=?,email=?,avaimg=?,password=?,address=? where id = ?`;
        await ctx.db.EXCUTE(sql, [res.managename, res.phone, res.email, imgurl, res.password, res.address, res.id]);
    }
    let sql = `select * from manage where id = '${res.id}'`;
    let result = await ctx.db.EXCUTE(sql)
    console.log(result)
    ctx.body = { data: result, status: "修改管理员信息成功" }
})

// 删除管理员信息
router.post('/delmanage', async function (ctx, next) {
    let id = ctx.request.body.id;
    let name = ctx.request.body.avaimg;
    if (name !== '') {
        let basePath = './public/manageavater/';
        var files = [];
        if (fs.existsSync(basePath)) {
            files = fs.readdirSync(basePath);
            files.forEach(function (file, index) {
                var curPath = path.join(basePath, file);
                if (fs.statSync(curPath).isDirectory()) {
                    deleteFile(curPath, file);
                } else {
                    if (file.indexOf(name) > -1) {
                        fs.unlinkSync(curPath);
                    }
                }
            });
        } else {
            console.log("给定的路径不存在！");
        }
    }
    let sql = `delete from manage where id = "${id}"`
    await ctx.db.EXCUTE(sql);
    ctx.body = { status: "删除管理员信息成功" }
})

module.exports = router